<script setup>
import {onMounted, ref} from 'vue'
import {Plus} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getApplyById, submitApply, updateApply} from "@/api/apply.js";
import {
  centsToYuan,
  formatDateFromArray,
  numberToType,
  typeToNumber
} from "@/utiles/typeConverter.js";
import {useRoute, useRouter} from "vue-router";


const route = useRoute()
const router = useRouter()
const form = ref({})
const plans = ref([])
const showDialog = ref(false)
const isEditing = ref(false)
const editingIndex = ref(-1)

onMounted(() => {
  form.value.id = route.query.id
  console.log(form.value.id)

  if (form.value.id !== undefined)
    getApply()
})
// 新行程计划数据
const newPlan = ref({
})

// 打开添加行程计划对话框
const addPlan = () => {
  // 重置新计划数据
  Object.keys(newPlan.value).forEach(key => {
    newPlan.value[key] = ''
  })
  showDialog.value = true
}

const confirmAddPlan = () => {
  // 验证数据
  if (!newPlan.value.type || !newPlan.value.detail || !newPlan.value.budgetDetail || !newPlan.value.budgetAmount) {
    ElMessage.error('请填写完整的行程计划信息')
    return
  }

  if (isEditing.value) {
    plans.value[editingIndex.value] = {
      id: newPlan.value.id,
      applyId: newPlan.value.applyId,
      type: typeToNumber(newPlan.value.type),
      detail: newPlan.value.detail,
      budgetAmount: newPlan.value.budgetAmount * 100,
      budgetDetail: newPlan.value.budgetDetail
    }
    isEditing.value = false
    ElMessage.success('行程计划更新成功')
  } else {
    // 添加新行程计划
    plans.value.push({
      id: newPlan.value.id,
      applyId: newPlan.value.applyId,
      type: typeToNumber(newPlan.value.type),
      detail: newPlan.value.detail,
      budgetAmount: newPlan.value.budgetAmount * 100,
      budgetDetail: newPlan.value.budgetDetail
    })
    ElMessage.success('行程计划添加成功')
  }
  // 关闭对话框
  showDialog.value = false

}
// 删除行程计划
const removePlan = (index) => {
  ElMessageBox.confirm(
    '确定要删除这个行程计划吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    plans.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

const editPlan = (index) => {
  // 设置状态为编辑模式
  isEditing.value = true
  editingIndex.value = index

  // 将当前行的数据填充到表单中
  const plan = plans.value[index]
  newPlan.value.id = plan.id
  newPlan.value.applyId = plan.applyId
  newPlan.value.type = numberToType(plan.type)
  newPlan.value.detail = plan.detail
  newPlan.value.budgetAmount = centsToYuan(plan.budgetAmount)
  newPlan.value.budgetDetail = plan.budgetDetail

  // 打开对话框
  showDialog.value = true
}

const saveApply = async (status) => {
  const apply = ref({
    userId: 10001,
    startTime: form.value.startTime,
    endTime: form.value.endTime,
    destination: form.value.destination,
    purpose: form.value.purpose,
    status: status,
    plans: plans.value
  })

  const res = await submitApply(apply.value);
  console.log(res)

  ElMessage({
    message: '差旅申请提交成功',
    type: 'success',
    center: true, // 居中显示
    duration: 2000 // 2秒后自动关闭
  })


  form.value={}
  plans.value=[]

  await router.push({
    name: 'ApplyManage'
  })

}

const getApply = async () => {
  const {data} = await getApplyById(form.value.id)
  console.log(data.data)
  form.value = data.data
  plans.value = data.data.plans
  form.value.startTime = formatDateFromArray(data.data.startTime)
  form.value.endTime = formatDateFromArray(data.data.endTime)
}

const editApply = async (status) => {
  const apply = ref({
    id: form.value.id,
    startTime: form.value.startTime,
    endTime: form.value.endTime,
    destination: form.value.destination,
    purpose: form.value.purpose,
    status: status,
    plans: plans.value
  })

  const res = await updateApply(apply.value);
  console.log(res)
  if (res.data.code === 1) {
    // 成功
    ElMessage({
      message: '更新成功',
      type: 'success',
      duration: 3000
    })

    await router.push({
      name: 'ApplyStatus',
      query: {
        id: form.value.id
      }
    })

    // 只有在成功时才清空表单
    form.value = {}
    plans.value = []
  } else {
    // 失败
    ElMessage({
      message: res.data.msg || '更新失败，请重试',
      type: 'error',
      duration: 5000
    })
  }

  }

</script>

<template>
  <div id="main">
    <div class="container">
      <div class="form-section">
        <h2 class="section-title">基本信息</h2>
        <div class="form-row">
          <div class="form-item">
            <label class="form-label">出差人</label>
            <el-input model-value="赵六" disabled></el-input>
          </div>
          <div class="form-item">
            <label class="form-label">出差开始时间</label>
            <el-date-picker
              style="width: 600px"
              v-model="form.startTime"
              type="date"
              placeholder="选择开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </div>
          <div class="form-item">
            <label class="form-label">出差结束时间</label>
            <el-date-picker
              style="width: 600px"
              v-model="form.endTime"
              type="date"
              placeholder="选择结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">目的地</label>
            <el-input v-model="form.destination" placeholder="请输入目的地"></el-input>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">出差事由</label>
          <el-input
            v-model="form.purpose"
            type="textarea"
            :rows="4"
            placeholder="请输入出差事由"
          ></el-input>
        </div>
      </div>

      <div class="table-section">
        <h2 class="section-title">行程计划</h2>
        <el-button class="add-plan-btn" @click="addPlan">
          <el-icon>
            <Plus/>
          </el-icon>
          添加行程计划
        </el-button>

        <el-table :data="plans" style="width: 100%" empty-text="暂无行程计划">
          <el-table-column prop="type" label="计划类型" width="120">
            <template #default="scope">
              {{ numberToType(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="details" label="计划明细">
            <template #default="scope">
              {{ scope.row.detail }}
            </template>
          </el-table-column>
          <el-table-column prop="budget" label="预算金额" width="120">
            <template #default="scope">
              {{ centsToYuan(scope.row.budgetAmount) }} 元
            </template>
          </el-table-column>
          <el-table-column prop="budgetDetails" label="预算明细">
            <template #default="scope">
              {{ scope.row.budgetDetail }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button
                class="edit-btn"
                size="small"
                @click="editPlan(scope.$index)"
              >
                编辑
              </el-button>
              <el-button
                class="delete-btn"
                size="small"
                @click="removePlan(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>


      </div>

      <div class="action-buttons">
        <span v-if="form.id===undefined">
          <el-button @click="saveApply(0)">保存草稿</el-button>
          <el-button type="primary" @click="saveApply(2)">提交申请</el-button>
        </span>
        <span v-else>
          <el-button @click="editApply(0)">保存草稿</el-button>
          <el-button type="primary" @click="editApply(2)">提交申请</el-button>
        </span>

      </div>
    </div>

    <el-dialog
      v-model="showDialog"
      :title="isEditing ? '编辑行程计划' : '添加行程计划'"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="newPlan" label-width="120px">
        <el-form-item label="行程计划类型：">
          <el-select v-model="newPlan.type" placeholder="请选择计划类型" style="width: 100%">
            <el-option label="交通" value="交通"></el-option>
            <el-option label="住宿" value="住宿"></el-option>
            <el-option label="餐饮" value="餐饮"></el-option>
            <el-option label="会议" value="会议"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行程计划明细：">
          <el-input
            v-model="newPlan.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入行程计划明细"
          ></el-input>
        </el-form-item>
        <el-form-item label="预算金额：">
          <el-input v-model="newPlan.budgetAmount" placeholder="0.00">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="预算明细：">
          <el-input
            v-model="newPlan.budgetDetail"
            type="textarea"
            :rows="2"
            placeholder="请输入预算明细"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmAddPlan">确定</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.container {
  max-width: 1200px;
  margin: 0 auto;
  background: #ffffff;
  padding: 30px;
  border: 1px solid #dddcdc;
}

.form-section {

  border-radius: 8px;
  width: 600px;
  margin: 0 auto;


  .section-title {
    font-size: 1.3rem;
    margin-bottom: 20px;
    font-weight: 500;
  }

  .form-row {
    display: grid;
    gap: 20px;
    margin-bottom: 20px;
  }

  .form-item {
    display: flex;
    flex-direction: column;
  }

  .form-label {
    margin-bottom: 8px;
    font-size: 0.95rem;
  }

}

.el-input, .el-textarea, .el-date-editor {
  width: 100%;
}

.el-input__inner, .el-textarea__inner {
  background: rgba(17, 34, 64, 0.7) !important;
  border: 1px solid rgba(100, 255, 218, 0.2) !important;
  color: #e6f1ff !important;
}

.el-input__inner::placeholder, .el-textarea__inner::placeholder {
  color: #8892b0 !important;
}

.el-input__inner:focus, .el-textarea__inner:focus {
  border-color: #64ffda !important;
}

.table-section {
  margin-top: 30px;

  .el-table {
    background: transparent !important;

    .el-table th {
      background: rgba(10, 25, 47, 0.8) !important;
      color: #64ffda !important;
      border-bottom: 1px solid rgba(100, 255, 218, 0.2) !important;
    }

    .el-table tr {
      background: rgba(17, 34, 64, 0.5) !important;
    }

    .el-table td {
      border-bottom: 1px solid rgba(100, 255, 218, 0.1) !important;
      color: #e6f1ff !important;
    }

    .el-table__empty-block {
      background: rgba(17, 34, 64, 0.5) !important;
    }

  }


}


.action-buttons {
  display: flex;
  margin-left: 300px;
  gap: 15px;
  margin-top: 30px;
}

.el-button {
  font-weight: 600;
  border-radius: 6px;
  transition: all 0.3s ease;
}


.el-button--default:hover {
  background: rgba(100, 255, 218, 0.1) !important;
  transform: translateY(-2px);
}

.delete-btn {
  color: #f14668 !important;
  border-color: #f14668 !important;
}

.delete-btn:hover {
  background: rgba(241, 70, 104, 0.1) !important;
}

.add-plan-btn {
  margin-bottom: 15px;
}

</style>
